<script lang="ts" setup>
import { useChatStore } from '@/store/chat'
import { useUIStore } from '@/store/ui'
import Avatar from '@/libs/Avatar/Avatar.vue'
import { formatMessageTime } from '@/utils/dateUtils'

// 使用从store导入的Contact类型
import type { Contact } from '@/store/chat/type'

interface Props {
  contact: Contact
  isSelected?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isSelected: false
})

const emit = defineEmits<{
  click: [contactId: string]
}>()

const chatStore = useChatStore()
const uiStore = useUIStore()

// 格式化联系人时间，处理各种情况
const formatContactTime = (contact: Contact): string => {
  // 优先使用lastSeen属性
  if (contact.lastSeen) {
    return formatMessageTime(contact.lastSeen)
  }

  // 如果没有lastSeen，尝试使用会话的最后活跃时间
  const session = chatStore.sessions.find((s) => s.id === contact.id)
  if (session && session.lastActiveTime) {
    return formatMessageTime(session.lastActiveTime)
  }

  // 如果都没有，返回固定时间格式
  return '09:00'
}

// 获取联系人的最后一条消息
const getLastMessage = (contact: Contact): string => {
  // 尝试从会话中获取最后一条消息
  const session = chatStore.sessions.find((s) => s.id === contact.id)
  if (session && session.lastMessage) {
    // 根据消息类型返回不同的预览文本
    switch (session.lastMessage.type) {
      case 'text':
        return session.lastMessage.content
      case 'image':
        return '[图片]'
      case 'file':
        return '[文件]'
      case 'voice':
        return '[语音]'
      case 'video':
        return '[视频]'
      default:
        return session.lastMessage.content
    }
  }

  // 如果没有会话或最后消息，尝试使用contact.lastMessage
  if (contact.lastMessage) {
    return contact.lastMessage
  }

  // 如果都没有，返回一个默认提示
  return contact.username || '点击开始聊天'
}

// 处理联系人点击
const handleClick = (): void => {
  emit('click', props.contact.id)

  // 查找或创建与该联系人的会话
  let session = chatStore.sessions.find((s) => s.participants.includes(props.contact.id))
  if (!session) {
    session = {
      id: props.contact.id,
      type: 'private' as const,
      name: props.contact.nickname,
      avatar: props.contact.avatar || '',
      unreadCount: 0,
      lastActiveTime: new Date(),
      participants: ['current-user', props.contact.id]
    }
    chatStore.addSession(session)
  }
  if (session) {
    chatStore.setActiveSession(session.id)
    uiStore.setActiveToolbarItem('chat')
  }
}
</script>

<template>
  <div class="contact-item" :class="{ selected: isSelected }" @click="handleClick">
    <div class="contact-avatar">
      <Avatar
        :src="contact.avatar"
        :alt="contact.nickname"
        :username="contact.nickname"
        :status="contact.status"
        size="medium"
      />
    </div>
    <div class="contact-info">
      <div class="contact-header">
        <span class="contact-name">{{ contact.nickname }}</span>
        <span class="contact-time">{{ formatContactTime(contact) }}</span>
      </div>
      <div class="contact-footer">
        <span class="contact-message">{{ getLastMessage(contact) }}</span>
        <div v-if="contact.isBlocked" class="blocked-badge">已屏蔽</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.contact-item:hover {
  background-color: var(--hover-bg-color);
}

.contact-item.selected {
  background-color: var(--primary-color-light, rgba(24, 144, 255, 0.1));
  border-left: 3px solid var(--primary-color, #1890ff);
}

.contact-item.selected:hover {
  background-color: var(--primary-color-light, rgba(24, 144, 255, 0.15));
}

.contact-avatar {
  margin-right: 16px;
  flex-shrink: 0;
}

.contact-info {
  flex-grow: 1;
  min-width: 0; /* 关键：让flex子项能够正确溢出 */
  overflow: hidden;
  width: calc(100% - 60px); /* 减去头像宽度和margin */
  max-width: 220px; /* 限制最大宽度 */
}

.contact-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  width: 100%;
  overflow: hidden; /* 确保内容不会溢出 */
}

.contact-name {
  font-size: 14px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 60%; /* 减小最大宽度，确保时间有足够空间 */
  display: inline-block; /* 确保宽度限制生效 */
}

.contact-time {
  font-size: 12px;
  color: var(--text-muted-color);
  flex-shrink: 0;
  min-width: 40px; /* 确保时间有最小宽度 */
  text-align: right; /* 右对齐时间 */
}

.contact-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  position: relative; /* 确保子元素可以相对于它定位 */
}

.contact-message {
  font-size: 12px;
  color: var(--text-muted-color);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-grow: 1;
  margin-right: 8px;
  max-width: 170px; /* 固定最大宽度，确保时间有足够空间 */
  width: 100%; /* 占满可用空间 */
  display: block; /* 确保宽度限制生效 */
}

.blocked-badge {
  background-color: var(--danger-color, #f5222d);
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 10px;
  text-align: center;
  font-weight: 500;
  flex-shrink: 0;
}
</style>
